package com.pmcc.core.service;

import com.pmcc.core.config.security.JwtTokenUtil;
import com.pmcc.core.config.security.JwtUser;
import com.pmcc.core.entity.Geographic;
import com.pmcc.core.entity.Label;
import com.pmcc.core.entity.Tags;
import com.pmcc.core.entity.User;
import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.entity.security.Organization;
import com.pmcc.core.entity.security.Role;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.repository.OrganizationRepository;
import com.pmcc.core.repository.RoleRepository;
import com.pmcc.core.repository.TagsRepository;
import com.pmcc.core.vo.TokenVo;
import com.pmcc.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by tomas on 18/4/9.
 */
@Service
@Transactional
public class EmployeeService {
    @Autowired
    EmployeeRepository employeeRepository;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    OrganizationRepository organizationRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    JwtTokenUtil jwtTokenUtil;



    @Autowired
    TagsRepository tagsRepository;

    @Value("${web.downloadFile}")
    private  String downloadFile;

    public ResultBean queryByPage(AntdPage antdPage, Employee model) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page = employeeRepository.findAll(this.getSpecifition(model), antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public Specification<Employee> getSpecifition(Employee model) {
        return new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<>();

                list.add(builder.equal(root.get("delFlag").as(Integer.class), 0));
                if (model.getSysOrgId() != null && !"".equals(model.getSysOrgId())) {
                    list.add(builder.equal(root.get("sysOrgId").as(String.class), model.getSysOrgId()));
                }
                if (model.getIds() != null && model.getIds().size() > 0) {
                    CriteriaBuilder.In in = builder.in((root.get("sysOrgId").as(String.class)));
                    for (String a : model.getIds()) {
                        in.value(a);
                    }
                    list.add(in);
                }
                Predicate[] p = new Predicate[list.size()];

                return builder.and(list.toArray(p));
            }
        };
    }

    /**
     * 新增
     *
     * @param employee
     * @return
     */
    public ResultBean addEmployee(Employee employee) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            employee.setCreateName(OnlineUser.getName());
            employee.setCreateTime(new Date());
            employee.setDelFlag(0);
            //设置初始密码
            employee.setPassword(encoder.encode("123456"));
            employeeRepository.saveAndFlush(employee);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("新增成功");
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 按机构编号查询人员
     *
     * @param code
     * @return
     */
    public ResultBean queryByCode(AntdPage antdPage, String code) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            //先查询出符合条件的组织id
            List<String> ids = organizationService.queryByCode(code);
            //查询出改组织集合下的人员
            Employee employee = new Employee();
            employee.setIds(ids);
            Page page = employeeRepository.findAll(this.getSpecifition(employee), antdPage.getPageRequest());
            List<Employee> list = page.getContent();
            if (list != null && list.size() > 0) {
                for (Employee emp : list) {
                    try {
                        emp.setOrganizationName(organizationRepository.getOne(emp.getSysOrgId()).getcName());
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(list);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    /**
     * 修改
     *
     * @param map
     * @return
     */
    public ResultBean update(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee c = employeeRepository.findById(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            employeeRepository.saveAndFlush(c);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(c);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public ResultBean deleteById(String id, Integer flag) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee f = employeeRepository.findById(id);
            f.setDelFlag(flag);
            employeeRepository.saveAndFlush(f);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(f);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 重置密码
     *
     * @param employee
     * @return
     */
    public ResultBean restPwd(Employee employee) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        try {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            employee.setPassword(encoder.encode("123456"));
            employeeRepository.save(employee);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }



    /**
     * 获取登录人信息
     *
     * @param token
     * @return
     */
    public User getEmployeeInfo(String token) {

        ResultBean resultBean = new ResultBean("1");

        Role role = new Role();//当前登陆人角色
        String sysRoleId = "";//角色id
        String sysOrgId = "";//组织id
        Organization organization = new Organization();//当前登陆人组织
        User user=new User();
        TokenVo tokenVo = new TokenVo();
        if (StringUtil.isNotEmpty(token)) {
            String username = jwtTokenUtil.getUsernameFromToken(token);
            Employee employee = employeeRepository.findByUserName(username);
            if (employee != null) {
                BeanUtils.copyProperties(employee, tokenVo);
                sysRoleId = employee.getSysRoleId();
                sysOrgId = employee.getSysOrgId();
                if (StringUtils.isNotEmpty(sysRoleId)) {
                    role = roleRepository.findById(sysRoleId);
                    if (role != null) {
                        tokenVo.setMenuKeys(role.getMenuKey());
                    }
                }
                if (StringUtils.isNotEmpty(sysOrgId)) {
                    organization = organizationRepository.findById(sysOrgId);
                    tokenVo.setSysOrgId(sysOrgId);
                    tokenVo.setSysOrgName(organization.getcName());
                    tokenVo.setSysOrgCode(organization.getCode());

                }
                //改造的用户信息
                user.setUserid(employee.getId());
                user.setAvatar(employee.getPhoto());
                user.setName(employee.getUserCname());
                user.setEmail(employee.getEmail());
                user.setPhone(employee.getMobile());
                user.setAddress(employee.getAddress());
                user.setCountry(employee.getCountry());
                user.setCity(employee.getCity());
                user.setProvince(employee.getProvince());
                user.setRemark(employee.getRemark());
                user.setSpareMailbox(employee.getSpareMailbox());
                //user.setNotifyCount("12");
                user.setSignature(employee.getSignature());
                user.setTitle(employee.getTitle());
                user.setGroup(organization.getcName()+" － "+role.getName());
                Geographic gs=new Geographic();
                gs.setCity(new Label("000",employee.getCity()));
                gs.setProvince(new Label("111", employee.getProvince()));
                user.setGeographic(gs);
                List<Tags> tagsList =tagsRepository.findByEmployeeId(employee.getId());
                List<Label> list=new ArrayList<>();
                for(Tags list1 : tagsList){
                    list.add(new Label(list1.getId(),list1.getTag()));
                }
                user.setTags(list);
            }
        } else {
            resultBean.setResultCode("0");
            resultBean.setResultDesc("token为空");
        }
        resultBean.setObject(tokenVo);

        return user;
    }
    /**
     * 更新基本信息按钮
     *
     */
    public ResultBean updateButton(User user) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findById(user.getUserid());
            employee.setUserCname(user.getName());
            employee.setEmail(user.getEmail());
            employee.setSignature(user.getSignature());
            employee.setTitle(user.getTitle());
            employee.setCountry(user.getCountry());
            employee.setCity(user.getCity());
            employee.setProvince(user.getProvince());
            employee.setAddress(user.getAddress());
            employee.setMobile(user.getPhone());
            //employee.setPhoto(user.getAvatar());
            employee.setRemark(user.getRemark());
            employeeRepository.saveAndFlush(employee);
            resultBean.setResultCode(ResultBean.SUCCESS);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    /**
     * 用户头像上传
     */
    public String upload(MultipartFile file, String employeeId) {
        // 上传的文件存放路径
        String uploadDiskPath = downloadFile;
        if (!file.isEmpty()) {
            try {
                String originalFilename = new String(file.getOriginalFilename());
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                // 存放在服务器端的文件名
                String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
                // 创建文件夹  年-月-日/goods
                String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String fileUrl = "/" + folder + "/" + serverFileName;

                Employee employee = employeeRepository.findById(employeeId);
                employee.setPhoto("/downloadFile"+fileUrl);
                employeeRepository.saveAndFlush(employee);
                File targetFile = new File(uploadDiskPath, fileUrl);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdir();
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的.";
        }
    }
    /**
     * 密码修改
     */
    public ResultBean saveNewPwd(String userId,String newPwd) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        try {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            Employee employee = employeeRepository.findById(userId);
            employee.setPassword(encoder.encode(newPwd));
            employeeRepository.saveAndFlush(employee);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    /**
     * 密保手机修改
     */
    public ResultBean saveNewPhone(String userId,String newPhone) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findById(userId);
            employee.setMobile(newPhone);
            employeeRepository.saveAndFlush(employee);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    /**
     * 备用邮箱修改
     */
    public ResultBean saveSpareMailbox(String userId,String spareMailbox) {
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        try {
            Employee employee = employeeRepository.findById(userId);
            employee.setSpareMailbox(spareMailbox);
            employeeRepository.saveAndFlush(employee);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * Tomas 2018-11-08 用于安卓端解决客户提出问题中
     */
    public List<Employee> leadEmployee(){
        Role role=roleRepository.findByName("设计部领导").get(0);
        return  employeeRepository.findBySysRoleId(role.getId());
    }

    /**
     * Tomas 2018-11-12  查询所有生产部装配工
     */
    public ResultBean getProduction(String currentAuthority){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        Role role=new Role();
        if(currentAuthority.equals("[SJBLEADER]")){
            role=roleRepository.findByName("设计部工程师").get(0);
        }else if("[SCBLEADER]".equals(currentAuthority)){
            role=roleRepository.findByName("生产部工程师").get(0);
        }
        List<Employee> list=employeeRepository.findBySysRoleId(role.getId());
        resultBean.setRows(list);
        return resultBean;
    }

}
